package com.yangrui.app.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.yangrui.app.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        if(!(obj instanceof HandlerMethod)){
            return true;
        }
        //请求的URL指向的方法没有@Token注解 直接放行
        Method method = ((HandlerMethod)obj).getMethod();
        if(!method.isAnnotationPresent(Token.class)){
            return true;
        }
        //从请求头获取token 没有再从请求参数获取
        String token = request.getHeader("token");
        if(token == null || "".equals(token)){
            token = request.getParameter("token");
        }
        //没有token直接拒绝访问
        if(token == null || "".equals(token)){
            throw new RuntimeException("token is null");
        }
        //解析token
        DecodedJWT verify = TokenUtil.verify(token);
        request.setAttribute("id",verify.getClaim("id").asInt());
        request.setAttribute("username",verify.getClaim("username").asString());
        request.setAttribute("avatar",verify.getClaim("avatar").asString());
        return true;
    }
}
